package com.linewow.xhyy.nihaonew.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.canyinghao.candialog.CanDialog;
import com.canyinghao.candialog.CanDialogInterface;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.hrxb.Constant;
import com.linewow.xhyy.hrxb.activity.ChatActivity;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.FrameActivity;
import com.linewow.xhyy.nihaonew.activity.TopicDetailActivity;
import com.linewow.xhyy.nihaonew.activity.UserMineActivity;
import com.linewow.xhyy.nihaonew.activity.account.LoginActivity;
import com.linewow.xhyy.nihaonew.adapter.FindTagTopicAdapter1;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.base.ListBaseFragmentNormal;
import com.linewow.xhyy.nihaonew.db.NiHaoHelper;
import com.linewow.xhyy.nihaonew.entity.NiHaoEntity;
import com.linewow.xhyy.nihaonew.entity.user.Uinfo;
import com.linewow.xhyy.nihaonew.entity.image.SimpleImagesInfo;
import com.linewow.xhyy.nihaonew.entity.tag.CustomTagsInfo;
import com.linewow.xhyy.nihaonew.entity.topic.FindTagTopicInfo;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.model.HttpModel;
import com.linewow.xhyy.nihaonew.util.NewsCallback;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import okhttp3.Call;

/**
 * Created by LXR on 2016/8/23.
 */
public class AttentionFragment extends ListBaseFragmentNormal implements BaseQuickAdapter.RequestLoadMoreListener {

    private FindTagTopicAdapter1 adapter1;
    private String TAG = "AttentionFragment";
    private String tagId;
    private Type tagDetailType;
    private Gson gson;
    private List<FindTagTopicInfo<Uinfo,SimpleImagesInfo,CustomTagsInfo>>findTagTopicInfos;
    private View contentView,includeView;
    private int page=0;

    private RecyclerView attentionRecycler;
    private boolean resumeFlag;//控制每次新登录用户时的刷新
//    private SwipeRefreshLayout swipeRefreshLayout;

    private PtrFrameLayout ptr;



    @Override
    protected void setUpView() {
        super.setUpView();
        contentView=View.inflate(getActivity(),R.layout.view_refresh_recycler,null);

        attentionRecycler= (RecyclerView) contentView.findViewById(R.id.view_refresh_recycler_view);
        ptr= (PtrFrameLayout) contentView.findViewById(R.id.view_refresh_listview_ptr);
        final MaterialHeader header = new MaterialHeader(getContext());
        int[] colors = getResources().getIntArray(R.array.google_colors);
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPtrFrameLayout(ptr);
        ptr.setHeaderView(header);
        ptr.addPtrUIHandler(header);
        ptr.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame,content,header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pullDown();
            }
        });

        attentionRecycler.setItemAnimator(new DefaultItemAnimator());
        LinearLayoutManager manager=new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        attentionRecycler.setLayoutManager(manager);

        findTagTopicInfos=new ArrayList<FindTagTopicInfo<Uinfo,SimpleImagesInfo,CustomTagsInfo>>();
        adapter1=new FindTagTopicAdapter1(findTagTopicInfos);
        adapter1.isFirstOnly(false);
        adapter1.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter1.setOnLoadMoreListener(AttentionFragment.this);
        attentionRecycler.setAdapter(adapter1);
        attentionRecycler.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void SimpleOnItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, final int i) {
                int id=view.getId();
                final FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>topicInfo=findTagTopicInfos.get(i);
                switch (id){
                    case R.id.widget_topic_menu_like_rela:
                        if(topicInfo.zan.equals("0")){
                            OkHttpUtils.post()
                                    .url(HttpModel.USERLIKE+"&token="+NiHaoApp.token+"&rid="+topicInfo.rid)
                                    .addParams("tid",topicInfo.tid)
                                    .addParams("tuid",topicInfo.uid)
                                    .build()
                                    .execute(new StringCallback() {
                                        @Override
                                        public void onError(Call call, Exception e, int id) {

                                        }

                                        @Override
                                        public void onResponse(String response, int id) {
                                            Log.e("AttentionFragment","回复"+response);
                                            topicInfo.setZan("1");
                                            int upnum=Integer.parseInt(topicInfo.upnum);
                                            topicInfo.setUpnum(Integer.toString(++upnum));
                                            adapter1.notifyItemChanged(i);

                                            String contents=getActivity().getResources().getString(R.string.message_zan_content);
                                            NiHaoHelper.getInstance().requestZan(topicInfo.uid,contents,topicInfo.rid);
                                        }
                                    });
                        }else{
                            Log.e("AttentionFragment","取消点赞了");
                            OkHttpUtils.post()
                                    .url(HttpModel.USERULIKE+"&token="+NiHaoApp.token+"&rid="+topicInfo.rid)
                                    .addParams("tuid",topicInfo.uid)
                                    .build()
                                    .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {
                                        @Override
                                        public void onError(Call call, Exception e, int id) {

                                        }

                                        @Override
                                        public void onResponse(NiHaoEntity response, int id) {
                                            if(response.status){
                                                Log.e("AttentionFragment","取消回复"+response);
                                                topicInfo.setZan("0");
                                                int upnum=Integer.parseInt(topicInfo.upnum);
                                                topicInfo.setUpnum(Integer.toString(--upnum));
                                                adapter1.notifyItemChanged(i);


                                            }
                                        }
                                    });
                        }
                        break;
                    case R.id.widget_topic_menu_conversation_img:
//                        final FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>topicInfo1=findTagTopicInfos.get(i);
                        Intent intent=new Intent(getActivity(), ChatActivity.class);
                        intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_SINGLE );
                        intent.putExtra(Constant.EXTRA_USER_ID, topicInfo.uid);
                        startActivity(intent);
                        break;

                    case R.id.widget_personal_message_avatar:
                        startUserActivity(topicInfo.uinfo);
                        break;

                }
            }
        });

        attentionRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Log.e(TAG,"详情活动");
                FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>topicInfo1=findTagTopicInfos.get(i);
                startDetailActivity(topicInfo1.tid);
            }
        });


        listBaseContent.addView(contentView);
        rightImg.setVisibility(View.GONE);
        leftImg.setVisibility(View.GONE);
        midTv.setText(getString(R.string.navigation_attention));
    }

    @Override
    public void initList() {
        super.initList();
        initGson();
        EventBus.getDefault().register(AttentionFragment.this);
        if(NiHaoApp.flag){
            onLoadingView();
            pullDown();
        }

        listener=new ListBaseListener() {
            @Override
            public void onLoginListener() {
                Intent intent=new Intent(AttentionFragment.this.getActivity(), LoginActivity.class);
                startActivity(intent);
            }

            @Override
            public void onRetryListener() {

            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
//        Log.e(TAG,"App"+NiHaoApp.flag+"---"+resumeFlag);
        if(NiHaoApp.flag&&resumeFlag){
            Log.e(TAG,"重新请求了");
            pullDown();
            resumeFlag=false;
        }
    }

    private void initGson() {
        gson=new Gson();
        tagDetailType=new TypeToken<BaseInfo<FindTagTopicInfo<Uinfo,SimpleImagesInfo,CustomTagsInfo>>>(){}.getType();
    }


    private void pullDown() {
        page=0;
        refreshData();
    }

    private void refreshData() {
        OkHttpUtils.get().url(HttpModel.TOPICATTENTION1+"&page="+page+"&token="+NiHaoApp.token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }
                    @Override
                    public void onResponse(String response, int id) {
                        finishLoadingView();
                        ptr.refreshComplete();
                        BaseInfo<FindTagTopicInfo<Uinfo,SimpleImagesInfo,CustomTagsInfo>>baseInfo=gson.fromJson(response,tagDetailType);
                        if(baseInfo.status){
                            if(baseInfo.data!=null){
                                findTagTopicInfos.clear();
                                adapter1.addData(baseInfo.data);
                                adapter1.notifyDataSetChanged();//一定要加这一步。。
                                adapter1.openLoadMore(5);
                                if(adapter1.getData().size()==0){
                                    onNoDataView();
                                }
                            }
                        }else{
                            if(baseInfo.info.equals("关注内容不能为空")){
                                Log.e(TAG,"关注内容为空--全部gone掉3");
                                findTagTopicInfos.clear();
                                adapter1.notifyDataSetChanged();//登录另外一个账号的时候
                                onNoDataView();
                                adapter1.loadComplete();

                                new CanDialog.Builder(AttentionFragment.this.getActivity())
                                        .setTitle(getString(R.string.menu_notice))
                                        .setMessage(getString(R.string.intelligent_attention_null))
                                        .setCircularRevealAnimator(CanDialog.CircularRevealStatus.TOP_LEFT)
                                        .setPositiveButton(getString(R.string.widget_sure), true, new CanDialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                                                ((FrameActivity)(AttentionFragment.this.getActivity())).frameActDataControl.find(null);
                                            }
                                        })
                                        .show();

                            }
                        }

                    }
                });

    }

    public void pullUp(){
        if(adapter1.getData().size()>=5){
            page++;
            loadData();
        }else{
            try {
                adapter1.loadComplete();
            }catch (Exception e){

            }

        }
    }
    private void loadData() {
        onLoadingView();
        OkHttpUtils.get().url(HttpModel.TOPICATTENTION2+"&page="+page+"&token="+NiHaoApp.token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }
                    @Override
                    public void onResponse(String response, int id) {
                        finishLoadingView();
                        BaseInfo<FindTagTopicInfo<Uinfo,SimpleImagesInfo,CustomTagsInfo>>baseInfo=gson.fromJson(response,tagDetailType);
                        List<FindTagTopicInfo<Uinfo,SimpleImagesInfo,CustomTagsInfo>> infos=baseInfo.data;
                        if(adapter1!=null){
                            adapter1.addData(infos);
                        }
                        if(infos.size()<5){
                            adapter1.loadComplete();
                        }
                    }
                });

    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(AttentionFragment.this);
    }

    @Subscriber(tag = "login",mode = ThreadMode.POST)
    public void getMessageEvent(MessageEvent messageEvent){
        resumeFlag=true;
    }

    @Subscriber(tag = "refresh",mode = ThreadMode.MAIN)
    public void refreshMessage(MessageEvent messageEvent){
        Log.e(TAG,"刷新了");
        resumeFlag=true;
    }

    @Override
    public void onLoadMoreRequested() {
        pullUp();
    }

//    @Override
//    public void onRefresh() {
//        pullDown();
//    }

    public void startDetailActivity(String tid){
        Intent intent=new Intent(AttentionFragment.this.getActivity(), TopicDetailActivity.class);
        intent.putExtra("msg",tid);
        startActivity(intent);
    }

    private void startUserActivity(Uinfo info) {
        Intent intent=new Intent(AttentionFragment.this.getActivity(), UserMineActivity.class);
        Bundle bundle=new Bundle();
        bundle.putParcelable("info",info);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
